/**
 * LayUI模块扩展规范
 * 以依赖layui的layer和form模块为例
    layui.define(['layer', 'form'], function(exports){
        var layer = layui.layer,form = layui.form;
        layer.msg('Hello World');
        exports('index', {}); //模块输出的核心,这句是必须的
    });
**/

layui.extend({
    "conf":"config",
    "xls":"lay/modules/xls",
    "view":"lay/modules/view",
    "menu":"lay/modules/menu"
}).define(["conf", "menu", "view", "xls", "jquery","table","form","layer","util","element"],function(exports){
    var $ = layui.jquery,
        conf = layui.conf,
        view = layui.view,
        menu = layui.menu,
        table = layui.table,
        form = layui.form,
        layer = layui.layer,
        util = layui.util,
        element = layui.element;
    var self = {};
    self.onmouseover = true;
    self.get = view.request;
    self.xls = layui.xls;
    self.route = layui.router();

    // 页面开始
    // 初始化菜单
    $("#navBar").html(layui.menu.initMenuHtml(menudata));
    // 检查页面链接地址是否已存储，刷新可回到当前页面
    if(self.route.href != undefined){
        var url = self.route.href;
        var obj = $("li [lay-href='"+url+"']");
        get_page(obj, "refresh");//在当前hash菜单addClass('layui-this')
    }
    //展开当前hash菜单组
    var thismenu = $('.nav-item .layui-this');
    thismenu.parents('.layui-nav-item').addClass('layui-nav-itemed');
    
    //todo 左侧导航菜单的显示和隐藏
    $('.header').on('click', '.layadmin-flexible', view.navigate);
    //点击遮罩背景，左侧菜单隐藏
    $('.layadmin-body-shade').on("click", view.shade);
    
    /*
     * @todo layui-nav菜单事件
     */
    $('.layui-top-menu,.layui-side-menu').on('click', '.nav-item a', function(event) {
        var obj = $(this);// 被点击的对象
        get_page(obj);
    });

    // 页面请求，获取页面内容
    function get_page(obj, type="click"){
        if(type=="refresh"){
            // console.log(obj.parent());
            obj.parent().addClass("layui-this");
        }
        var url = obj.attr('lay-href');// 链接地址
        var title = obj.find('cite').html();// 菜单标题（即页面子标题）
        var hassub = obj.siblings("dl").length ? true : false;// 是否有子菜单
        if(hassub == false){
            //防止重复点击菜单给服务器造成压力
            if(self.route.hash == url){
                return;
            }
            if(self.route.hash != url){
                self.route.hash = url;
                window.location.hash = url;
            }
            // 弹出加载提示
            var index = layer.msg('页面加载中,请稍候...', {
                icon: 16,
                time : false,
                shade: 0.01
            });
            // 构造请求和回调
            var params = {
                url: url,
                success: function(data) {
                    layer.close(index);// 关闭加载提示框
                    view.fix_document_title(title);
                    view.fix_breadcrumb(title);
                    view.fill_html(".main", data);
                    view.sidebar_ctrl("hidden");
                    form.render();
                    // 表单提交事件监听
                    form.on("submit(go)", function(data){
                        var elem = $(this),
                            field = data.field,
                            option = elem.attr("id");
                        view.btn_disable(elem);
                        switch(option){
                            case "account_search":
                                active.account_search(field, elem);
                                break;
                            case "flow_search":
                                active.flow_search(field.uid, elem);
                                break;
                            case "notice":
                                active.notice(option, field.content, field.worker, elem);
                                break;
                            case 'recharge_artifical':
                                active.recharge_artifical(field, elem);
                                break;
                            case 'modify_pass':
                                active.modify_pass(field.worker, field.password, field.newpass, field.repass, elem);
                                break;
                            case "worker_create":
                                active.worker_create(field, elem);
                                break;
                            default:
                                view.btn_enable(elem);
                                break;
                        }
                        return false;
                    })
                }
            }
            // 发起请求，获取内容
            self.get(params);
        }else{
            $('.layadmin-tabspage-none').removeClass("layadmin-side-shrink");// 防止含有子菜单的项目无法被展开
        }
    }

    //注册一些事件，方便后面使用
    var active = {
        // 操作类
        //通道维护
        channel: function(option, callback, elem=null){
            var params = {
                data: {
                    operation: option
                },
                url: "/index/operationc/change_channel",
                success: function(response){
                    layer.msg(response.message);
                    if(response.status == 1){
                        callback(option);//更改按钮状态
                    }
                }
            }
            self.post(params);
        },
        // 发公告
        notice : function(fn, cont, worker, elem=null){
            var params = {
                data: {
                    cont: cont,
                    worker: worker
                },
                url: "/index/operationc/put_notice",
                success: function(response){
                    layer.msg(response.message);
                    view.btn_enable(elem);
                }
            }
            self.post(params);
        },
        // recharge_artifical
        recharge_artifical: function(field, elem=null){
            var params = {
                data: {
                    uid: field.uid,
                    amount: field.amount,
                    attch: field.attch,
                    worker: field.worker
                },
                url: "/index/rechargec/recharge_artifical",
                success: function(response){
                    layer.msg(response.message);
                    view.btn_enable(elem);
                }
            }
            self.post(params);
        },
        // flowing
        flow_search : function(uid=0,elem=null) {
            if(uid){
                var params = {
                    data: {uid:uid},
                    url: "/index/customerc/account_flow",
                    success: function(response){
                        if(response.code == 1){
                            $(".sum-recharge").text(response.data.recharge).attr("title",response.data.recharge);
                            $(".sum-consumption").text(response.data.consumption).attr("title",response.data.consumption);
                            $(".sum-cash").text(response.data.cash).attr("title",response.data.cash);
                            $(".sum-scores-consumption").text(response.data.scores_consumption).attr("title",response.data.scores_consumption);
                            $(".sum-scores-simple").text(response.data.scores_simple).attr("title",response.data.scores_simple);
                        }else{
                            layer.msg(data.message);
                        }
                        view.btn_enable(elem);
                    }
                }
                self.post(params);
            }else{
                layer.msg("请输入用户ID...");
                view.btn_enable(elem);
            }
            view.btn_enable(elem);
        },
        // account
        account_search : function(field,elem=null) {
            if(field.uid){
                var params = {
                    data: {uid: field.uid},
                    url: "/index/customerc/account",
                    success: function(data){
                        if(data.status==1){
                            //渲染表格
                            table.render({
                                elem:"#accountTable",
                                page:true,
                                limit:5,
                                limits:[5,10,20],
                                cols:self.xls.account,
                                data:data.data
                            })
                        }else{
                            layer.msg(data.message);
                        }
                        view.btn_enable(elem);
                    }
                }
                self.post(params);
            }else{
                layer.msg("请输入用户ID...");
                view.btn_enable(elem);
            }
        },
        modify_pass: function(worker, password, newpass, repass, elem){
            var params = {
                data: {worker:worker, password:password, newpass:newpass, repass:repass},
                url: "/index/workerc/modify_pass",
                success: function(data){
                    layer.msg(data.message);
                    view.btn_enable(elem);
                }
            }
            self.post(params);
        },
        worker_able: function(field, option, elem) {
            var worker = field.account;
            var params = {
                url: '/index/workerc/worker_able',
                data: {worker: worker, option: option},
                success: function(data) {
                    if(data){
                        var msg = "操作成功"
                        elem.siblings(".btn-able").removeClass("layui-btn-disabled").attr("disabled", false);
                        elem.addClass("layui-btn-disabled").attr("disabled", true);
                    }else{
                        var msg = "操作失败";
                    }
                    layer.msg(msg);
                    return;
                }
            }
            self.post(params);
        },
        worker_repass: function(field, option, elem){
            var worker = field.account;
            var params = {
                url: "/index/workerc/worker_repass",
                data: {worker:worker, option: option},
                success: function(data) {
                    layer.msg(data.message);
                }
            }
            self.post(params);
        },
        worker_create: function(field, elem){
            var worker = field.account,
                nik = field.nickname,
                sex = field.sex,
                identity = field.identity,
                birthday = field.birthday,
                role = field.role;
            var params = {
                url: "/index/workerc/worker_create",
                data: {worker: worker, nik: nik, sex:sex , identity:identity , birthday:birthday , role: role},
                success: function(data) {
                    layer.msg(data.message,view.btn_enable(elem));//表单提交，需要将提交按钮还原成可用的状态
                }
            }
            self.post(params);
        },
        /**
         * [reload 数据表格重载]
         * @param  [string] tableID    [必须，要重载的表格ID]
         * @param  [string] fieldName  [必须，要提交的参数名称]
         * @param  [string/int] fieldValue [必须，要提交的参数值]
         */
        reload : function(tableID, fieldName, fieldValue){//表格重载
            //执行重载
            table.reload(tableID,{
                page:{
                    curr:1 //重新从第 1 页开始
                },
                where:{
                    /*
                     * [fieldName] - 必须用方括号包裹变量，否则将被视为字面量，ES6+
                     * ES5 写法如下:
                     * var keyname = "keyname";
                     * var keyvalue = "keyvalue";
                     * var obj = {};
                     * obj[keyname] = keyvalue;
                     */
                    key:{[fieldName]: fieldValue}
                }
            },'data');// 只重载数据
        },
        laymsgtimer : function(obj,layero){//提示信息关闭倒计时器
            var msg_text = obj.content;
            var i = Math.round(obj.time/1000);
            var msgtimer = null;
            var fn = function() {
                layero.find(".layui-layer-content").text(msg_text + "(" + i + ")");
                if(!i) {
                    clearInterval(msgtimer);
                } 
                i--;
            };
            msgtimer = setInterval(fn, 1000);
            fn();
        },
        showtips : function(obj,side=2){
            /**
             * side tips显示位置，可选值1-top,2-right,3-bottom,4-left
             */
            layer.tips(obj.text(),obj,{
                time: 0,
                tips: [side, '#3595CC'],
                success: function(layero, index) {
                    obj.on("mouseleave",function(){
                        layer.close(index);
                    })
                }
            })
        }
    };

    //事件委托
    // 卡片面板，显示完整内容-showtips
    $(".layui-layout-admin").on("mouseover",".layuiadmin-card-list a",function(e) {
        obj = $(this);
        timer = setTimeout(function(){
            active.showtips(obj);
        },800); //鼠标悬停0.8秒后显示tips
    }).on("mouseout", ".layuiadmin-card-list a", function(){
        clearTimeout(timer);
    });
    // 卡片面板链接点击事件，查明细
    $(".layui-layout-admin").on("click",".layuiadmin-card-list a",function(e) {
        var search_type = $(this).attr("layui-type"),
            search_model = "page",
            uid = $("#uid").val();
        if($("#uid").length > 0){search_model = "form";}
        if(search_model == "page"){
            switch(search_type){
                case "other":
                default:
                    layer.msg("对不起，您指定的项目没有明细可供查询...");
                    return;
                    break;
            }
            self.post({
                "url":"/index/incomec/"+search_type,
                "success":function(data){
                    if(data.code==1){
                        table.render({
                            elem: '#incomeTable',//推荐使用ID选择器
                            cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                            page: true,
                            limit:5,
                            limits:[5,10,20],
                            cols: cols,
                            data: data.data
                        });
                    }else{
                        layer.msg(data.message);
                    }
                }
            })
        }
        if(search_model == "form"){
            if(uid){
                switch(search_type){
                    case "recharge":
                        cols = self.xls.recharge_details;
                        break;
                    case "consumption":
                        cols = self.xls.consumption_details;
                        break;
                    case "cash"://id,account,flag,atime,htime,name,bank,rbank,card
                        cols = self.xls.cash_details;
                        break;
                    case "scores_consumption":
                        cols = self.xls.scores_consumption_details;
                        break;
                    case "scores_simple":
                        cols = self.xls.scores_simple_details;
                        break;
                    default:
                        layer.msg("对不起，您指定的项目没有明细可供查询...");
                        return;
                        break;
                }
                // 异步数据接口
                table.render({
                    elem: '#flowTable',//推荐使用ID选择器
                    method: "post", //layui默认使用get方式
                    url: "/index/customerc/"+search_type,
                    cols: cols,
                    where:{
                        key:{uid: uid}
                    },
                    cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    page: true,
                    limit:5,
                    limits:[5,10,20],
                    response: {
                        statusName: 'status', //规定数据状态的字段名称，默认：code
                        statusCode: 1, //规定成功的状态码，默认：0
                        msgName: 'message', //规定状态信息的字段名称，默认：msg
                        countName: 'count', //规定数据总数的字段名称，默认：count
                        dataName: 'data' //规定数据列表的字段名称，默认：data
                    }
                    // ,parseData: function(res){ // 将原始数据解析为layui.table组件所规定的
                    //     return {
                    //         "code": res.code, // 解析请求状态
                    //         "msg": res.message, // 解析文本信息
                    //         "count": res.count, // 解析数据长度
                    //         "data": res.data    // 解析数据列表
                    //     }
                    // }
                });
                /*
                赋值已知数据的方式，适用数据量较小的项目
                $.ajax({
                    "type":"post",
                    "data":{"uid":uid},
                    "url":"/index/flow/"+search_type,
                    "dataType":"json",
                    "success":function(data){
                        //data = JSON.parse(data);//解析TP返回的json
                        if(data.code==1){
                            table.render({
                                elem: '#flowTable',//推荐使用ID选择器
                                cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                                page: true,
                                limit:5,
                                limits:[5,10,20],
                                cols: cols,
                                data: data.data
                            });
                        }else{
                            layer.msg(data.message);
                        }
                    }
                })
                */
            }else{
                layer.msg("请输入用户ID...");
            }
        }
        return false;
    });
    
    //通道开/关
    $(".layui-body").on("click",".channel .layui-btn",function(){
        var obj = $(this);
        var option = obj.attr("id");
        var optionSibling = obj.parent().siblings().children(".layui-btn").attr("id");
        var changeBtnStatus = function(param){
            if(option == "channel_start"){//全开
                $(".layui-btn-danger").removeAttr("disabled").removeClass("layui-btn-disabled");
                $(".layui-btn-normal").attr("disabled",true).addClass("layui-btn-disabled");
            }else if(option == "channel_stop"){//全关
                $(".layui-btn-normal").removeAttr("disabled").removeClass("layui-btn-disabled");
                $(".layui-btn-danger").attr("disabled",true).addClass("layui-btn-disabled");
            }else{//开\关
                $("#" + optionSibling).removeAttr("disabled").toggleClass("layui-btn-disabled");
                obj.attr("disabled",true).toggleClass("layui-btn-disabled");
            }
        }
        active.channel(option, changeBtnStatus, obj);
    });

/*-----------------------------------*/

    // 数据表格(自动渲染方式)重载
    /**
     * 核心：call()
     * this指向调用某个方法的对象，使用call()和apply()方法会改变this的指向
     * 语法：object.call(thisOject, arg1, arg2, ...)
     * 解析：用object方法(对象)替换thisOject(对象)运行，arg1,arg2 是object方法的实参。
     */
    $(".layui-body").on("click",".account-list .layui-btn, .rechartifical-list .layui-btn, .rechplatform-list .layui-btn", function(){
        var obj = $(this);
        var type = obj.data('type');
        var table = obj.attr("id").split(/[-_]/),
            tableID = table[0]+"Reload";//lower、account、更多
        form.on("submit(go)",function(data){
            var field = data.field;
            var fieldName,fieldValue;
            $.each(field, function(key, value){
                fieldName = key;
                fieldValue = value;
            });
            //重载数据表格
            if(tableID == "lowerReload"){
                switch(field.status){
                    case "0":
                    case "1":
                    case "2":
                    case "all":
                        active[type] ? active[type].call(this, tableID, fieldName, fieldValue) : '';//执行重载active.reload
                        break;
                    default:
                        layer.msg("请选择查询条件...");
                        break;
                }
            }else{
                if(field[fieldName] != ""){
                    active[type] ? active[type].call(this, tableID, fieldName, fieldValue) : '';//执行重载active.reload
                }else{
                    layer.msg("请设置查询条件...");
                }
            }
            return false;
        });
    });

    //监听行内单击事件
    table.on('tool(flowing)', function(obj){
        var data = obj.data;//获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值
        var tr = obj.tr; //获得当前行 tr 的DOM对象
        if(layEvent === 'room_detail'){
            layer.open({
                type: 1,
                title: '详情查看',
                area: ['100%', '100%'],
                btn: '我知道了',
                btnAlign: 'c',// align:center
                shade: 0,
                content: $("#view-details-div"),//这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                success: function(layero, index){
                    table.render({
                        elem: "#details",
                        cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                        cols: self.xls.flowing_details,
                        data: data.details
                    });
                }
            }); 
        }
    });
    
    table.on('tool(accountTb)', function(e){
        var data = e.data;//获得当前行数据
        var layEvent = e.event; //获得 lay-event 对应的值
        var obj = $(this),
            option = obj.data('type'),
            optionTxt = obj.text();
        layer.open({
            type: 1,
            title: '操作提示',
            area: '100%',
            btn: ['确定','取消'],
            btnAlign: 'c',
            shade: 0,
            content:    "<div class='lay-alert'>您确定要<span class='" + option + "'>" + 
                        optionTxt + "</span>用户<span class='id'>" + data.uid + "</span>的账户吗？</div>",
            yes: function(index, layero){
                active.player_able("player_" + option, data.uid, obj);
                layer.close(index);
            }
        });
    });

    table.on('tool(workerTb)', function(e){
        var data = e.data;//获得当前行数据
        var layEvent = e.event; //获得 lay-event 对应的值
        var obj = $(this),
            option = obj.data("type"),
            optionTxt = obj.text();
        var content = "";
        switch(layEvent){
            case "worker_able":
                content = "<div class='lay-alert'>您即将<span class='" + option + "'>" + 
                        optionTxt + "</span>管理员账户 ：<span class='id'>" + data.account + 
                        "</span>，您确定要继续执行该操作吗？</div>";
                break;
            case "worker_repass":
                content = "<div class='lay-alert'>您即将<span class='" + option + "'>重置</span>管理员账户：<span class='id'>" + 
                        data.account + "</span>的密码，您确定要继续执行该操作吗？</div>";
                break;
            default:break;
        }
        layer.open({
            type: 1,
            title: '操作提示',
            area: '100%',
            btn: ['确定','取消'],
            btnAlign: 'c',
            shade: 0,
            content: content,
            yes: function(index, layero){
                active[layEvent](data, option, obj);
                layer.close(index);
            }
        }); 
    });

    /**
     * 全局AJAX错误信息处理
     * @param  [object] jqXHR            [$.ajax()返回的XMLHTTPRequest对象的超集]
     * @param  [string] textStatus       [状态码，可能的值：timeout(超时),error(错误),abort(中止),parsererror(解析错误),NULL(空值)]
     * @param  [string] errorThrown      [服务器抛出返回的错误信息]
     */
    $.ajaxSetup({
        error:function(jqXHR, textStatus, errorThrown){
            layer.closeAll();
            switch (jqXHR.status){
                case 900:
                    layer.msg("登录超时，请重新登录，即将为您跳转至登录页...",{
                        //time:5000,
                        success:function(layero,index){//active.laymsgtimer
                            active.laymsgtimer(this,layero);
                        },
                        end:function(){
                            location.href = conf.loginPage;
                        }
                    });
                    break;
                case "(canceled)":
                    console.log("连接服务器超时...");
                    break;
                case 500:
                    layer.msg("服务器内部错误");
                    break;
                case 401:
                    layer.msg("未登录");
                    break;
                case 403:
                    layer.msg("无权限执行此操作");
                    break;
                case 408:
                    layer.msg("请求超时");
                    break;
                default:
                    layer.msg("操作失败",{
                        success:function(layero,index){//active.laymsgtimer
                            active.laymsgtimer(this,layero);
                        }
                    });
                    break;
            }
        }
    });
   //修改ajax数据传输形式为post
   self.post = function(params) {
        //jQuery.extend()用于将一个或多个对象的内容合并到目标对象。
        view.request($.extend({ type: 'post' }, params))
    }
    util.fixbar({});//topbar
    element.init();//初始化
    exports('admin', self);//注意，模块输出的核心，名称必须和use时的一致
});